package com.ruoyi.product.service.impl;

import java.sql.Array;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.constant.HttpStatus;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.product.es.ProdEs;
import org.apache.commons.lang3.ObjectUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import com.ruoyi.product.mapper.TbProdMapper;
import com.ruoyi.product.domain.TbProd;
import com.ruoyi.product.service.ITbProdService;

/**
 * 商品列表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-08
 */
@Service
public class TbProdServiceImpl implements ITbProdService {
    @Autowired
    private TbProdMapper tbProdMapper;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;


    /**
     * 查询商品列表
     *
     * @param prodId 商品列表主键
     * @return 商品列表
     */
    @Override
    public TbProd selectTbProdByProdId(Integer prodId) {
        return tbProdMapper.selectTbProdByProdId(prodId);
    }

    /**
     * 查询商品列表列表
     *
     * @param tbProd 商品列表
     * @return 商品列表
     */
    @Override
    public List<TbProd> selectTbProdList(TbProd tbProd) {
        return tbProdMapper.selectTbProdList(tbProd);
    }

    /**
     * 新增商品列表
     *
     * @param tbProd 商品列表
     * @return 结果
     */
    @Override
    public int insertTbProd(TbProd tbProd) {
        tbProd.setCreateTime(DateUtils.getNowDate());
        return tbProdMapper.insertTbProd(tbProd);
    }

    /**
     * 修改商品列表
     *
     * @param tbProd 商品列表
     * @return 结果
     */
    @Override
    public int updateTbProd(TbProd tbProd) {
        tbProd.setUpdateTime(DateUtils.getNowDate());
        return tbProdMapper.updateTbProd(tbProd);
    }

    /**
     * 批量删除商品列表
     *
     * @param prodIds 需要删除的商品列表主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdIds(Integer[] prodIds) {
        return tbProdMapper.deleteTbProdByProdIds(prodIds);
    }

    /**
     * 删除商品列表信息
     *
     * @param prodId 商品列表主键
     * @return 结果
     */
    @Override
    public int deleteTbProdByProdId(Integer prodId) {
        return tbProdMapper.deleteTbProdByProdId(prodId);
    }

    @Override
    public AjaxResult createIndexEs() {
        IndexOperations indexOps = restTemplate.indexOps(ProdEs.class);
        boolean exists = indexOps.exists();
        if (exists) {
            indexOps.delete();
        }
        indexOps.create();
        Document mapping = indexOps.createMapping();
        indexOps.putMapping(mapping);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult syncProdEs() {
        List<TbProd> prods = tbProdMapper.selectTbProdList(new TbProd());
        for (TbProd prod : prods) {
            ProdEs prodEs = BeanUtil.toBean(prod, ProdEs.class);
            restTemplate.save(prodEs);
        }

        return AjaxResult.success();
    }

    @Override
    public TableDataInfo getProdListByEs(TbProd prod, Integer pageNum, Integer PageSize) {
        //构造分页参数
        PageRequest pageOf = PageRequest.of(pageNum - 1, PageSize);

        //创建查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (ObjectUtils.isNotEmpty(prod.getProdName())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("prodName", prod.getProdName()));
        }


        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>").postTags("</font>").field("prodName");

        //根据id倒序排列
        FieldSortBuilder sortBuilder = SortBuilders.fieldSort("prodId").order(SortOrder.DESC);

        //查询
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder
                .withPageable(pageOf)
                .withQuery(boolQueryBuilder)
                .withSorts(sortBuilder)
                .withHighlightBuilder(highlightBuilder);

        SearchHits<ProdEs> hits = restTemplate.search(queryBuilder.build(), ProdEs.class);

        ArrayList<ProdEs> list = new ArrayList<>();

        for (SearchHit<ProdEs> hit : hits.getSearchHits()) {
            ProdEs prodEs = hit.getContent();
            List<String> prodName = hit.getHighlightField("prodName");
            if (prodName != null && prodName.size() > 0) {
                prodEs.setProdName(prodName.get(0));
            }
            list.add(prodEs);
        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setRows(list);
        rspData.setMsg("查询成功");
        rspData.setTotal(hits.getTotalHits());

        return rspData;


    }


}
